package com.googlecode.afdbaccess.web.common.interceptors;

import javax.inject.Inject;
import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;
import javax.transaction.UserTransaction;

import org.apache.log4j.Logger;

import com.googlecode.afdbaccess.config.injectconfig.ManagedRequestTransaction;

@DatabaseAccessing
@Interceptor
public class UserTransactionManagagerInterceptor {
    private final static Logger log = Logger.getLogger(UserTransactionManagagerInterceptor.class);

    @Inject
    UserTransaction userTransaction;
    
    @Inject
    private ManagedRequestTransaction t;

    @AroundInvoke 
    public Object rollbackAtException(InvocationContext ctx) throws Exception {
        Object returnObject;
        boolean completed = false;

        try {
            t.setSource(InterceptorsCommon.getPageDescription(InterceptorsCommon.findRequest(ctx)));
            userTransaction.begin();
            try {
                returnObject = ctx.proceed();
            } finally {
                t.close();
            }
            completed = true;
            userTransaction.commit();
        } finally {
            if(!completed) {
                log.info("Rolling back transaction since method didn't complete properly. Exception will be handled below.");
                try {
                    userTransaction.rollback();
                } catch (Exception e) {
                    log.info("Exception when trying to roll back transaction. Ignoring: ", e);
                }
            }
        }
        return returnObject;
    }

}